#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <string>
#include <pthread.h>
#include <cstdio>
#include <cstring>
#include <functional>
#include "Log.hpp"

namespace ThreadModel
{
    using namespace LogModel;
    MutexModel::Mutex lock;

    static uint32_t number = 1;

    class Thread
    {
        using func_t = std::function<void()>;

    private:
        // 类内静态成员函数可以：静态成员函数没有 this 指针，签名能精准匹配 void* (*)(void*)，满足 pthread_create 的要求。
        // 可直接访问类的静态成员；通过 args 传递 this 后，可访问非静态成员（如你代码里的 self->_func()）
        static void *Routine(void *arg)
        {
            Thread *self = static_cast<Thread *>(arg);
            self->EnableRunning();
            // if(self->_isdetach)
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }
        void EnableRunning()
        {
            _isrunning = true;
        }
    public:
        
        Thread(func_t func) : _tid(0), _isdetach(false), _isrunning(false), _func(func), res(nullptr)
        {
            MutexModel::Guard lockguard(&lock);
            _name = "thread-" + std::to_string(number++);
        }
        bool Start()
        {
            if (_isrunning)
                return false;
            else
            {
                int n = pthread_create(&_tid, nullptr, Routine, this);
                void *(n);
            }
        }
        bool Stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                    return false;
                else
                {
                    _isrunning = false;
                    return true;
                }
            }
            return false;
        }
        bool Join()
        {
            if (_isrunning)
            {
                int n = pthread_join(_tid, &res);
                if (n != 0)
                {
                    Log(LogLevel::DEBUG) << "线程join失败";
                    return false;
                }
                Log(LogLevel::DEBUG) << "线程join成功";
                _isrunning = false;
                return true;
            }
        }

        bool Detach()
        {
            if (_isdetach)
                return true;
            else
            {
                pthread_detach(_tid);
                _isdetach = true;
                return true;
            }
        }
        ~Thread() {}

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
    };
}

#endif